package com.zxl.admin.aspect;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zxl.admin.context.UserContext;
import com.zxl.common.exception.BusinessException;
import com.zxl.common.mapper.SysRoleMapper;
import com.zxl.common.mapper.SysUserRoleMapper;
import com.zxl.common.model.pojo.SysUserRole;
import com.zxl.common.service.SysRoleService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author zxw
 * @date 2023/4/6
 */
@Aspect
@Component
public class PowerAspect {

    @Resource
    private SysRoleService sysRoleService;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    @Pointcut("execution(public * com.zxl.admin.controller..*.*(..))"
                + " &&!@annotation(com.zxl.admin.annotation.NoPower)")
    public void power() {
    }

    @Around("power()")
    @RequestMapping
    public Object arround(ProceedingJoinPoint pjp) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        SysUserRole sysUserRole = sysUserRoleMapper.selectOne(new QueryWrapper<SysUserRole>()
                .eq("user_id", UserContext.getUserId()));

        /**  管理员  **/
        if(sysUserRole.getRoleId().equals(1)){
            return pjp.proceed();
        }

        String url = request.getRequestURI().replaceFirst("//", "/");
        /** 判断用户是否有该url的权限 **/
        String s = sysRoleService.checkUrl(url, sysUserRole.getRoleId());
        if( s!=null ){
            throw new BusinessException(s);
        }

        return pjp.proceed();

    }

}
